import axios from "axios";
import { BASE_API,  SCREEN_API, TASK_API,ACCOUNT_API,EXPORT_API, TIMEOUT10, TIMEOUT5 } from "./config_my_axios.mjs"
// import qs from "qs";
import chalk from 'chalk';
const errorStyle = chalk.whiteBright.bgRedBright.bold
const fineStyle = chalk.bgGreenBright.bold
const infoStyle = chalk.underline
class MyRequest {
  constructor(baseURL, timeout) {
    this.instance = axios.create({
      baseURL,
      timeout
    })
    this.instance.interceptors.request.use(
      // 在发送请求之前做些什么
      (config) => {
        console.log('in pre req: config: ', config)
        return Promise.resolve(config)
      },
      // 对请求错误做些什么
      (error) => {
        console.log(errorStyle(`${infoStyle('request error')}: ${error.response}`));
        return Promise.reject(error);
      });
    this.instance.interceptors.response.use(
      // 对响应数据做点什么
      (response) => {
        console.log(fineStyle(`response: ${response.data}`));
        return response.data;
      },
      // 对响应错误做点什么
      (error) => {
        console.log(errorStyle(`${infoStyle('response error')}: ${error.response}`));
        return Promise.reject(error.response);
      });
  }

  request(config) {
    return new Promise((resolve, reject) => {
       try {
        this.instance.request(config).then(res => {
          resolve(res);
        }).catch(err => {
          console.log(errorStyle(`${infoStyle('resolve error')}: ${err}`))
          reject(err);
        });
      } catch (err) {
        console.log(errorStyle(`${infoStyle('request error')}: ${err}`))
        reject(err)
      }
    })
  }

  get(_url, _params = {}, _config = {}) {
    if (!_url) throw "Error: None URL"
    return this.request({
      url: _url, method: 'get', params: new URLSearchParams(_params),
      ..._config
    })
  }

  post(_url, _data = {}, _config = {}) {
    if (!_url) throw "Error: None URL"
    return this.request({
      url: _url, method: 'post', data: _data,
      ..._config
    })
  }
}

const MyRequestBase = new MyRequest(BASE_API, TIMEOUT5)
const MyRequestScreen = new MyRequest(SCREEN_API, TIMEOUT5)
const MyRequestTask = new MyRequest(TASK_API, TIMEOUT10)
const MyRequestExport = new MyRequest(EXPORT_API, TIMEOUT5)
const MyRequestAccount = new MyRequest(ACCOUNT_API, 1000)
export {MyRequestBase, MyRequestScreen, MyRequestTask, MyRequestExport,MyRequestAccount}